<?php
/**
 * Description: 获取试卷练习
 * User: devforma
 * Date: 15/4/13
 * Time: 20:38
 */

require __DIR__ . '/includes/utils.php';
class GetPaperExercise implements iController {
    /**
     * 缓存时间
     *
     */
    protected $_expires = 1800;
    
    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $cmsdb;
        
        $allowedtype = array('mokao', 'entire', 'mock', 'evaluate');
        if (empty($queryArgs['paper_id']) || !in_array($queryArgs['paper_type'], $allowedtype))
            return genOutput(1000);

        switch($queryArgs['paper_type']) {
            case 'mokao'; //mini模考
                $paperInfo = $cmsdb->getRow('SELECT * FROM `qb_paper_mokao` WHERE `id`=:paper_id',
                    array('paper_id' => $queryArgs['paper_id']));

                if (empty($paperInfo))
                    return genOutput(1000);

                return genOutput(1, array(
                    'paper_id' => intval($queryArgs['paper_id']),
                    'paper_name' => $paperInfo->name,
                    'duration' => 900,
                    'questions' => getQuestionsByIds(explode(',', $paperInfo->question_ids)),
                ));

            case 'entire': //整卷练习
            case 'evaluate': //估分
                $paper = getZtkPaper($queryArgs['paper_id']);
                if (empty($paper)) return genOutput(1000);
                
                $questions = getZtkQuestions($paper->id);
                
                return genOutput(1, array(
                    'paper_id' => intval($paper->id),
                    'paper_name' => $paper->name,
                    'duration' => intval($paper->duration),
                    'category' => $this->makeCategorys($questions)
                ));

            case 'mock': //模考
                $paperInfo = $this->getMockPaper($queryArgs['paper_id']);
                if ($paperInfo === false) return genOutput(1000);

                //记录模考进入次数
                $this->recordMockEnter($queryArgs['paper_id']);

                return genOutput(1, $paperInfo);
            
            default:
                return genOutput(1000);
        }
    }

    /**
     * 记录模考进入次数
     *
     * @param $mockId
     */
    function recordMockEnter($mockId) {
        //记录模考点击次数
        $cacheKey = 'mockClickCount:'.$mockId;
        if ($count = cacheGet($cacheKey)) {
            cacheIncrement($cacheKey, 1); //点击数+1
        } else {
            cacheAdd($cacheKey, 1, 48*60*60); //缓存两天
        }
    }

    /**
     * 生成科目题目格式
     * @param array $questionRows 题目信息数组
     * @return array
     */
    private function makeCategorys(&$questionRows) {
        //根据科目分组
        $category = array();
        foreach ($questionRows as $q) {
            if (!isset($category[$q->category]))
                $category[$q->category] = array(
                    'id' => getQuestionCategory($q->category),
                    'name' => $q->category,
                    'questions' => array(),
                    'answers' => array()
                );

            $category[$q->category]['questions'][] = $q->id;
        }

        //每个科目获取题目信息
        foreach ($category as &$catInfo) {
            $catInfo['questions'] = getQuestionsByIds($catInfo['questions']);
        }

        //科目排序
        $category2 = array();
        isset($category['常识判断']) and ($category2[] = $category['常识判断']);
        isset($category['言语理解与表达']) and ($category2[] = $category['言语理解与表达']);
        isset($category['数量关系']) and ($category2[] = $category['数量关系']);
        isset($category['判断推理']) and ($category2[] = $category['判断推理']);
        isset($category['资料分析']) and ($category2[] = $category['资料分析']);

        return $category2;
    }
    
    /**
     * 获取模考试卷信息
     *
     * @param int $id 试卷ID
     * @return array 试卷不存在时返回false
     */
    private function getMockPaper($id) {
        global $cmsdb;


        if (isset($_GET['original']) && $_GET['original'] == '1') {
            $cacheKey = 'mock:paper:original:' . $id;
        } else {
            $cacheKey = 'mock:paper:' . $id;
        }
        $paperInfo = cacheGet($cacheKey);
        if ($paperInfo) return $paperInfo;
        
        $sql = "SELECT * FROM `{$cmsdb->testPaper}` WHERE `id`=:id AND `paper_type` IN ('gufen', 'mokao')";
        $paper = $cmsdb->getRow($sql, array(':id' => $id));
        
        if (empty($paper)) {
            cacheAdd($cacheKey, false, $this->_expires);
            return false;
        }
        
        $questions = null;
        if ($id == 63) { //第一期按照number来排序
            $sql = "SELECT `id`, `category` FROM `{$cmsdb->oZtkQuestions}` "
                . " WHERE `id` IN ({$paper->ordered_question_ids}) "
                . " ORDER BY `number` ASC";
        } else {
            $sql = "SELECT `id`, `category` FROM `{$cmsdb->oZtkQuestions}` "
                . " WHERE `id` IN ({$paper->ordered_question_ids}) "
                . " ORDER BY FIELD (`id`, {$paper->ordered_question_ids})";
        }
        $questions = $cmsdb->getResults($sql);
        
        $paperInfo = array(
                        'paper_id' => intval($paper->id),
                        'paper_name' => $paper->paper_name,
                        'duration' => intval($paper->duration),
                        'category' => empty($questions) ? array() : $this->makeCategorys($questions)
                    );
        
        cacheAdd($cacheKey, $paperInfo, $this->_expires);
        
        return $paperInfo;
    }
}